package servlet;

import domain.Product;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @Author admin
 * @Date 2019/2/27 14:40
 */
@WebServlet(name = "addServlet",urlPatterns = "/addServlet")
public class addServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Product product = new Product();
        try {
            BeanUtils.populate(product,request.getParameterMap());
            ProductServiceImpl service = new ProductServiceImpl();
            service.add(product);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("/findAll").forward(request,response);
        /*创建工厂*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        /*创建文件解析工具*/
        ServletFileUpload upload = new ServletFileUpload();
        try {
            /*对request对象进行解析，得到FileItem的集合*/
            List<FileItem> fileItems=upload.parseRequest(request);
            for (FileItem item:fileItems){
                /*普通表单数据（只有两类，普通表单和文件）*/
                if (item.isFormField()){
                    /*如果为pname,将其设置到product的pname属性中*/
                    if (item.getFieldName().equals("pname")){
                        String value=item.getString();
                        product.setPname(value);
                    }
                    if (item.getFieldName().equals("marketprice")){
                        product.setMarketprice(Double.parseDouble(item.toString()));
                    }
                }else{
                    //文件
                    String fileName=item.getName();
                    System.out.println(fileName);

                }
            }
        } catch (FileUploadException e) {

        }


    }
}
